<!--
 * @Author: xiaotiwen
 * @Date: 2020-05-08 18:14:48
 * @LastEditTime: 2020-07-29 15:29:31
 * @LastEditors: xiaotiwen
 * @FilePath: \eduweb\src\views\practiceManagement\fundingManagement\index.vue
 * @Description: 经费管理
 -->

<template>
    <div class="fundingManagement">
        <inner-breadcrumb v-model="pathKey" :path="path"></inner-breadcrumb>
        <div v-if="pathKey==='main'">
            <ConditionCard shadow="never" label-width="110px" @search="onSubmit" @reset="reset('queryForm')">
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item :label="$t('label.schoolTerm')">
                                <CalendarSelect v-model="queryForm.yearTerm" @load-done="loadDone"></CalendarSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('label.grade')">
                                <el-date-picker v-model="queryForm.grade" value-format="yyyy" type="year" :placeholder="$t('message.plzSelect')" style="width: 100%" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('label.trainingLevel')">
                                <DictSelect v-model="queryForm.trainingLevel" :data="options.trainingLevel" :clearable="false" :disabled="true"></DictSelect>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item :label="$t('fundingManagement.label.courseOpenAcademy')">
                                <DictSelect v-model="queryForm.courseOpenAcademyId" :data="options.courseOpenAcademyId" :clearable="false" :filterable="true"></DictSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('courseConfirmation.label.stuFaculty')">
                                <DictSelect
                                    v-model="queryForm.studentAcademyId"
                                    :data="options.studentAcademyId"
                                    :clearable="false"
                                ></DictSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('label.major')">
                                <MyMajor :faculty="queryForm.studentAcademyId" :grade="queryForm.grade" v-model="queryForm.majorId"> </MyMajor>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item :label="$t('fundingManagement.label.isClassBorrow')">
                                <DictSelect v-model="queryForm.isClassBorrow" :data="options.isPlaceMent" :clearable="false"></DictSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('courseSummary.aduitType')">
                                <DictSelect v-model="queryForm.status" :data="options.status" :clearable="false"></DictSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item :label="$t('message.startTime')">
                                <el-date-picker v-model="queryForm.validDateStart" :placeholder="$t('message.plzSelect')" @change="timeChange" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%;"></el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item :label="$t('message.endTime')">
                                <el-date-picker v-model="queryForm.validDateEnd " :placeholder="$t('message.plzSelect')" @change="timeChange" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%;"></el-date-picker>
                            </el-form-item>
                        </el-col>

                    </el-row>
            </ConditionCard>
            <el-card shadow="never" body-style="padding: 24px;">
                <h2 class="fundingManagement_titles">{{$t('fundingManagement.title.indexTitle')}}</h2>
                <div class="edu-opertion-bar">
                    <div class="float-left">
                        <KeywordInput v-model="queryForm.courseIdOrNo" :placeholder="$t('courseConfirmation.tips.keyTips')" @enter="handSearchChang"></KeywordInput>
                        <!-- <el-input style="width: 200px;" v-model="queryForm.courseIdOrNo" maxlength="30" :placeholder="$t('courseConfirmation.tips.keyTips')" prefix-icon="el-icon-search" @change="handSearchChang" /> -->
                    </div>
                    <div class="float-right">
                        <!-- <el-dropdown @command="exportFile">
                            <el-button>{{$t('entry.export')}}<i class="el-icon-arrow-down el-icon--right"></i></el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item command="all">导出经费管理统计表</el-dropdown-item>
                                <el-dropdown-item command="selection">导出勾选记录</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown> -->
                        <el-button type="primary" v-if="authsBtnState.exportState" @click="exportFile">{{$t('message.export')}}</el-button>
                    </div>
                </div>
            </el-card>
            <div>
                <edu-table ref="tables" :data="data" :order="true" :orderFixed="true" :total="total" :pageSize="page.pageSize_" @page-change="handleSizeChange" :selectFixed='true'>
                    <el-table-column :min-width="item.width" align="center" v-for="(item, idx) in label" :key="item.props" :label="item.label" :prop="item.props" :sortable="item.sortable" show-overflow-tooltip :fixed="item.fixed"></el-table-column>
                    <el-table-column min-width="80" align="center" :label="$t('courseSummary.aduitType')" prop="status" fixed="right">
                        <template slot-scope="scope">
                            <el-tag type="info" v-if="scope.row.status === 'DRAFT'">{{$t('message.draft')}}</el-tag>
                            <el-tag v-else-if="scope.row.status === 'INPROCESS'">{{$t('message.checkPending')}}</el-tag>
                            <el-tag type="success" v-else-if="scope.row.status === 'APPROVED'">{{$t('practiceManagement.status.approved')}}</el-tag>
                            <el-tag type="danger" v-else-if="scope.row.status === 'REJECTED'">{{$t('practiceManagement.status.rejected')}}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" width="180px" :label="$t('message.operating')" fixed="right">
                        <template slot-scope="scope">
                            <div class="fundingManagement_btns" @click.stop="">
                                <el-button type="text" v-if="isShowApplyButton(scope.row)"
                                  @click="applyFunding('apply', scope.row)">{{$t('fundingManagement.btn.apply')}}</el-button>
                                <el-button type="text" v-else-if="(scope.row.status === 'INPROCESS')&&authsBtnState.reviewState" @click="applyFunding('audit', scope.row)">{{$t('message.check')}}</el-button>
                                <el-button type="text" v-if="scope.row.status === 'APPROVED'&&authsBtnState.printClaimFormState" @click="applyFunding('print', scope.row)">{{$t('fundingManagement.title.detailPageTitle')}}</el-button>
                                <el-button type="text" v-if="(scope.row.status === 'APPROVED')&&authsBtnState.reviewState" @click="reApply(scope.row)">{{$t('message.reject')}}</el-button>
                                <el-button type="text" v-if="authsBtnState.detailsState" @click="applyFunding('details', scope.row)">{{$t('message.detail')}}</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </edu-table>
            </div>
        </div>
        <!-- 报销单详情 /经费审核/打印报销单-->
        <fundingManagementDetails ref="details" v-if="pathKey==='details'||pathKey==='audit'||pathKey==='print'" :ids="ids" :fundId="fundId" @quit="cancel" :type="types" :dataInfo="dataInfo"
        :pathKey="pathKey" :fromCheckDetail="fromCheckDetail"> </fundingManagementDetails>
        <!-- 经费申请 -->
        <fundingManagementApply ref="apply" v-if="pathKey==='apply'" :ids="ids" @quit="pathKey='main'" @back:reload="reload"> </fundingManagementApply>
        <!-- 经费审核 -->
        <!-- <fundingManagementDetails ref="audit" v-if="pathKey==='audit'" :ids="ids" @quit="pathKey='main'"> </fundingManagementDetails> -->
        <!-- 打印报销单 -->
        <!-- <fundingManagementDetails ref="print" v-if="pathKey==='print'" :ids="ids" @quit="pathKey='main'" type="print"> </fundingManagementDetails> -->
    </div>
</template>

<script>
import { findDept } from 'common/src/api/user'
import fundingManagementDetails from './fundingManagementDetails';
import fundingManagementApply from './fundingManagementApply';
import commonMixins from '../commonMixins';
import moment from 'moment';
import { getList, exportData, reApply } from 'common/src/api/practiceManagement/fundingManagement';
import MyMajor from "common/src/views/practiceManagement/common/MyMajor";
import mixin from 'common/src/mixins/index';
export default {
    // 组件名称
    name: 'fundingManagement',
    // 局部注册的组件
    components: {
        fundingManagementDetails,
        fundingManagementApply,
        MyMajor
    },
    mixins: [commonMixins,mixin],
    // 组件参数 接收来自父组件的数据
    props: {
      type:{
        type: String,
      },
      dataInfo: {
        type: Object,
        default: {}
      },
    },
    // 组件状态值
    data() {
        return {
            page: {
                pageNum_: 1,
                pageSize_: 20
            },
            fundId: '',
            yearTerms: '',
            total: 0,
            ids: '',
            types: '',
            queryForm: {
                yearTerm: '', // 学年学期
                grade: '', // 年级
                trainingLevel: 'UDG', // 培养层次
                courseOpenAcademyId: '', // 学院院系
                studentAcademyId:'',//学生所属学院
                majorId: '', // 专业
                courseIdOrNo: '', // 课程代码或名称
                isPlaceMent: '', // 是否排课
                isClassBorrow: '', // 教室借用
                validDateStart: null, // 开始时间
                validDateEnd: null, // 结束时间
            },
            options: {
                trainingLevel: [{ label: this.$t('courseConfirmation.udg'), value: 'UDG' }, { label: this.$t('courseConfirmation.pre'), value: 'asdf' }], // 培养层次
                courseOpenAcademyId: [], // 院系
                studentAcademyId:[],//学生所属学院
                majorId: [], // 专业
                isPlaceMent: [{ label: this.$t('practiceManagement.yes'), value: 'Y' }, { label: this.$t('practiceManagement.no'), value: 'N' }], // 是否排课，是否教室借用
                status: [
                    { label: this.$t('practiceManagement.status.draft'), value: 'DRAFT' },
                    { label: this.$t('practiceManagement.status.inProcess'), value: 'INPROCESS' },
                    { label: this.$t('practiceManagement.status.approved'), value: 'APPROVED' },
                    { label: this.$t('practiceManagement.status.rejected'), value: 'REJECTED' }
                ]
            },
            pathKey: this.$route.query.pathKey?this.$route.query.pathKey:'main',
            path: {
                label: this.$t('fundingManagement.title.indexPath'),
                key: 'main',
                disable: false,
                children: [
                    { label: this.$t('fundingManagement.title.pageTitle'), key: 'apply', disable: true },
                    { label: this.$t('message.detail'), key: 'details', disable: true },
                    { label: this.$t('fundingManagement.title.detailPageTitle'), key: 'print', disable: true },
                    { label: this.$t('fundingManagement.title.pageTitle2'), key: 'audit', disable: true }
                ]
            },
            data: [],
            label: [
                { label: this.$t('fundingManagement.label.courseProgramNumber'), props: 'subCourseNo', width: 100, sortable: true, fixed: 'left' },
                { label: this.$t('fundingManagement.label.courseCode'), props: 'courseCode', width: 100, sortable: true, fixed: 'left'  },
                { label: this.$t('fundingManagement.label.courseName'), props: 'courseName', width: 180, fixed: 'left'  },
                { label: this.$t('fundingManagement.label.courseOpenAcademy'), props: 'courseOpenAcademy', width: 150 },
                { label: this.$t('label.grade'), props: 'grade', width: 80 },
                { label: this.$t('courseConfirmation.label.stuFaculty'), props: 'studentAcademy', width: 150 },
                { label: this.$t('fundingManagement.label.majorName'), props: 'majorName', width: 150 },
                { label: this.$t('fundingManagement.label.studentCount'), props: 'studentCount', width: 100, sortable: true },
                { label: this.$t('fundingManagement.label.times'), props: 'courseDate', width: 180, sortable: true },
                { label: this.$t('fundingManagement.label.courseAddr'), props: 'courseAddr', width: 130, sortable: true },
                { label: this.$t('fundingManagement.label.mainTeacherName'), props: 'mainTeacherName', width: 100, sortable: true },
                { label: this.$t('fundingManagement.label.funds'), props: 'funds', width: 90, sortable: true },
                { label: this.$t('fundingManagement.label.isClassBorrow'), props: 'isClassBorrow', width: 100, sortable: true }
            ],
            auths: [],
            authsBtnState: {
              reviewState: false, // 审核
              exportState: false,   // 导出
              detailsState: false, // 详情
              applyForFundingState: false, // 申请经费
              printClaimFormState: false,  // 打印报销单
            }
        };
    },
    // 计算属性
    computed: {},
    // 侦听器
    watch: {
      auths: {
        handler(newVal) {
          if (newVal && Array.isArray(newVal) && newVal.length > 0) {
            newVal.some(item => {
              // 审核
              if (item.authCode === 'fundingManagement-review') {
                this.authsBtnState.reviewState = true;
              }
              // 导出
              if (item.authCode === 'fundingManagement-export') {
                this.authsBtnState.exportState = true;
              }
              // 详情
              if (item.authCode === 'fundingManagement-details') {
                this.authsBtnState.detailsState = true;
              }
              // 申请经费
              if (item.authCode === 'fundingManagement-applyForFunding') {
                this.authsBtnState.applyForFundingState = true;
              }
              // 打印报销单
              if (item.authCode === 'fundingManagement-printClaimForm') {
                this.authsBtnState.printClaimFormState = true;
              }
            });
          }
        }
      }
    },
    /**
    * 在实例初始化之后，组件属性计算之前，如data属性等
    */
    created() {
      // 获取当前用户auths权限
      if (localStorage.getItem("sessiondata")) {
        if (JSON.parse(localStorage.getItem("sessiondata")).auths) {
          this.auths = JSON.parse(localStorage.getItem("sessiondata")).auths;
        }
      }
    },
    /**
    * 在挂载开始之前被调用：相关的 render 函数首次被调用。
    */
    mounted() {
        let param = {
            X_YX: 'courseOpenAcademyId' // 学院
        };
        this.initOptions(param);
        this.yearTerms = JSON.parse(JSON.stringify(this.queryForm.yearTerm));
        if(this.global.isAnyTeacher){
            let teacher = this.global.currentUser
            if(teacher.manageFaculty){
                this.options.courseOpenAcademyId.push({label:teacher.facultyName,value:teacher.faculty})
            }
        }
        findDept(0).then(res => {
            if (res.code == 200 && res.data) {
                this.options.studentAcademyId = res.data.map(row => {
                    return { label: row.deptName, value: row.deptCode }
                })
            }
        })
    },
    // 组件方法
    methods: {
        isShowApplyButton(row){
          let teacherJobno = row.mainTeacherJobno + ',' +  row.instructorTeacherJobno + ','
           return (teacherJobno.indexOf(this.global.currentUser.uid)!= -1)&&(row.status === 'DRAFT'||!row.status||row.status === 'REJECTED')&&this.authsBtnState.applyForFundingState;
        },
        applyFunding(val, row) {
            this.fundId = row.fundId;
            this.ids = row.id;
            this.types = val;
            if (val === 'apply') {
                this.fundTimeSetBtns(row.yearTerm).then(res => {
                    if (res) {
                        this.pathKey = val;
                    }
                });
            } else {
                this.pathKey = val;
            }
        },
        exportFile(type) { // 导出
            let selection = this.$refs.tables.selectionDatas;
            let params = {
                exportType: 0,
                request: this.queryForm,
                responses: selection
            }
            if (selection && selection.length >= 1) {
                params.exportType = 1;
            }
            exportData(params);
        },
        reload() { // 刷新页面
            this.getLists(true);
        },
        handleSizeChange(val) { // 分页数量事件
            [this.page.pageSize_, this.page.pageNum_] = [val.pageSize, val.pageNum];
            this.getLists();
        },
        handSearchChang() { // 搜索
            this.page.pageNum_=1
            this.getLists();
        },
        reset() { // 重置
            for (const key in this.queryForm) {
                if (key !== 'yearTerm') {
                    this.queryForm[key] = '';
                }
            }
            this.queryForm.yearTerm = this.yearTerms;
            this.queryForm.trainingLevel = 'UDG';
            this.getLists(true);
        },
        onSubmit() { // 筛选
            this.getLists(true);
        },
        getLists(refresh) { // 获取列表数据
            let flags = this.timeChange();
            if (!flags) {
                if(refresh){
                    this.page.pageNum_ = 1;
                    if(this.$refs.tables) {
                      this.$refs.tables.pageNum = 1;
                    }
                }
                let jsons = {
                    condition: this.queryForm,
                    pageNum_: this.page.pageNum_,
                    pageSize_: this.page.pageSize_
                };
                getList(jsons).then(res => {
                    this.data = res.data.list;
                    this.data.forEach(item => {
                        let startTime = '无';
                        let endTime = '无';
                        if (item.courseDateStart) {
                            startTime = moment(item.courseDateStart).format('YYYY-MM-DD');
                        }
                        if (item.courseDateEnd) {
                            endTime = moment(item.courseDateEnd).format('YYYY-MM-DD');
                        }
                        if (!item.courseDateStart && !item.courseDateEnd) {
                            this.$set(item, 'courseDate', '');
                        } else {
                            this.$set(item, 'courseDate', `${startTime}~${endTime}`);
                        }
                        this.$set(item, 'isClassBorrow', this.changeType(item.isClassBorrow, this.options.isPlaceMent));
                    });
                    this.total = res.data.total_;
                });
            }
        },
        timeChange() { // 开始时间结束时间判断
            if (this.queryForm.validDateStart && this.queryForm.validDateEnd) {
                if (this.queryForm.validDateStart > this.queryForm.validDateEnd) {
                    this.$message({ type: 'warning', message: this.$t('dispersionPracticeApply.tips.timeCheck') });
                    return true;
                }
            }
        },
        loadDone() { // 页面加载时保存学期学年
            this.yearTerms = this.queryForm.yearTerm;
            this.getLists();
        },
        cancel(val) {
            if (val === 'refresh') {
                this.getLists(true);
            }
            this.pathKey = 'main';
        },
        reApply(row){
            reApply(row.fundId).then(res => {
                if(res && res.code === 200){
                    this.$message({ message: this.$t('dispersionPracticeApply.tips.rejectSuc'), type: 'success' });
                    this.getLists(true);
                }
            })
        }
    }
};
</script>
<style lang="scss" scoped>
.fundingManagement {
    &_titles {
        font-weight: bold;
        color: #2b3b4e;
    }
    &_btns {
        display: flex;
        justify-content: space-between;
        &_btns {
            white-space: nowrap;
            cursor: default;
            width: 70px;
            text-align: center;
            padding: 2px 0;
            border-radius: 2px;
            border: solid #ccc 1px;
        }
        &_success {
            color: #67c23a;
            background-color: #fff;
            border: solid 1px #67c23a;
        }
        &_danger {
            color: #f56c6c;
            background-color: #fff;
            border: solid 1px #f56c6c;
        }
    }
}
</style>
